<template>
  <div class="content">
    <jc-button
      :btn-arr="['reload', 'newy', 'sub', 'remove', 'option', 'pass', 'push']"
      :disab-arr="['close', 'cancel', 'freeze', 'com2', 'com1', 'copy']"
      :fbillno="fbillno"
      @audit="audit(1)"
      @noAudit="audit(2)"
      @submit="submit(1)"
      @noSubmit="submit(2)"
      @refresh="detailsListHandle"
      @newly="addMateril"
      @del="delPublic"
      @toExcel="handleExportDetails"
      @startUsing="using(1)"
      @forbidden="using(2)"
      @pushDown="pushDown"
    />
    <div class="header">
      <div class="header-name">
        <search
          :options="selectData"
          :search-son="searchSon"
          :msg="tacitly"
          @seek="collect"
          @hand="detailsListHandle()"
        />
        <el-button
          type="primary"
          class="btn"
          size="mini"
          @click="detailsListHandle()"
        >
          {{ $t('btn.search') }}
        </el-button>
        <filtration
          :ftype="ftype"
          :msg="tacitly"
          :table-header="tableHeader1"
          :select-data="selectData"
          @seachData="detailsListHandle"
        />
      </div>
    </div>
    <div class="table-content">
      <jc-table
        v-loading="loading"
        :table-data="detailsData"
        :table-header="detailsHeader"
        :table-height="tableHeight"
        table-selection
        sortable
        get-row-keys="fentryId"
        @selectionChange="selectionDatas"
        @clickRow="detailPurchase"
      >
        <template v-slot:billSlot="clo">
          <el-link
            type="primary"
            @click="detailPurchase(clo.scope.row.fid)"
          >
            {{ clo.scope.row.fbillNo }}
          </el-link>
        </template>
        <!--    物料编码    -->
        <template v-slot:orderSlot="col">
          <el-link type="primary" @click="jumpMateriel(col.scope.row)">
            {{ col.scope.row.fnumber }}
          </el-link>
        </template>
        <!--    关闭状态    -->
        <template v-slot:tagSlot="clo">
          <el-tag v-if="clo.scope.row.fcloseStatus === '正常'">{{ $t('market.normal') }}</el-tag>
          <el-tag v-else-if="clo.scope.row.fcloseStatus === '已关闭'">
            {{ $t('market.closed') }}<!-- 已关闭 -->
          </el-tag>
          <span v-else />
        </template>
        <!--    状态    -->
        <template v-slot:btnState="col">
          <span v-if="col.scope.row.fdocumentStatus === ''" />
          <el-tag
            v-else
            :type="col.scope.row.stateColor"
          >
            {{ col.scope.row.fdocumentStatus }}
          </el-tag>
        </template>
      </jc-table>
      <!--    分页器-->
      <div class="footer">
        <jc-pagination
          v-show="totalDatail > 0"
          :total="totalDatail"
          :page.sync="currentPageDetail"
          :limit.sync="sizeDetail"
          @pagination="detailsList"
        />
      </div>
    </div>
    <el-dialog
      v-dialogDrag
      :title="$t('market.checkBill')"
      model
      :visible.sync="isdanjuDialog"
      :close-on-click-modal="false"
      width="600px"
      center
    >
      <div style="text-align: center;height: 100px;line-height: 100px">
        <el-radio-group v-model="orderLX" @change="orderWat">
          <el-radio v-for="item in receipts" :key="item" :label="item">{{ item }}</el-radio>
        </el-radio-group>
      </div>
      <hr>
      <div style="text-align: center;">
        {{ $t('market.rule') }}
        <el-input v-model="convert" size="mini" disabled style="width: 178px;margin-bottom: 5px;" />
        <br>
        {{ $t('market.billType') }}
        <el-select
          v-model.trim="fbillTypeId"
          size="mini"
          filterable
        >
          <el-option
            v-for="(item, index) in billTypeData"
            :key="index"
            :label="item.fname"
            :value="item.fid"
          />
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isdanjuDialog = false">{{ $t('btn.cancel') }}</el-button>
        <el-button size="mini" type="primary" @click="pushDownOrder()">{{ $t('btn.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  pushSalorder,
  queryViewItem
} from '@/api/marketManage/marketOrder'
import {
  queryTSalFoList, delSalFo,
  unCloseSalFo, closeSalFo,
  notreviewSalFo, reviewSalFo,
  notsubmitSalFo, submitSalFo
} from '@/api/marketManage/forecast'
import search from '@/components/Search'
import searData from '@/components/Search/mixin'
import { toMxAmina } from '@/components/ToMxamineState'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'
import { numFormat } from '@/utils/number'
import filtration from '@/components/filtration'
import jcButton from '@/components/Button'
import { queryPushDelSal } from '@/api/purchaseManagement/purchaseOrder'
export default {
  name: 'MarketOrder',
  components: {
    jcButton,
    search,
    filtration
  },
  mixins: [searData],
  data() {
    return {
      ftype: 6,
      total: 0, // 总条目
      currentPage: 1, // 当前页
      size: 200, // 每页显示多少条数据
      activeName: 'first',
      fbillno: '',
      orderLX: this.$t('menu.purOrderAsi'),
      receipts: [this.$t('menu.purOrderAsi'), this.$t('menu.deliveryRelease')], // 下推'采购订单''发货通知单'
      fentryData: [],
      billTypeData: [],
      fbillTypeId: 159,
      convert: this.$t('market.xafa'),
      isdanjuDialog: false, // 单据类型
      // 表头
      tableData: [], // 销售数据
      selectVal: [], // 删除销售订单数组
      fbillNoDetails: '',
      flowChart: '',
      totalDatail: 0,
      currentPageDetail: 1,
      sizeDetail: 200,
      detailsData: [],
      detailVal: '',
      detailsHeader: [
        { label: this.$t('market.date'), prop: 'fdate' },
        { label: this.$t('market.order'), type: 'bill', width: '130' },
        { label: this.$t('market.paezText1'), prop: 'fpaezText', minWidth: '100' },
        { label: this.$t('market.cust'), prop: 'customer', width: '100' },
        { label: this.$t('market.saler'), prop: 'fsaler', width: '80' },
        {
          label: this.$t('shop.state'),
          type: 'state',
          prop: 'fdocumentStatus',
          width: '80'
        },
        { label: this.$t('market.closeState'), type: 'tag', prop: 'fcloseStatus', width: '80' },
        { label: this.$t('market.fmodel'), prop: 'fmodel' },
        {
          label: this.$t('market.custmatNo'),
          prop: 'fcustmatNo',
          width: '80'
        },
        {
          label: this.$t('market.fmaterial'),
          type: 'order',
          prop: 'fnumber',
          width: '130'
        },
        { label: this.$t('shop.fname2'), prop: 'fname', width: '120' },
        {
          label: this.$t('shop.specifica'),
          prop: 'fspecificaTion',
          width: '100'
        },
        { label: this.$t('market.funit'), prop: 'funit', width: '80' },
        { label: this.$t('market.fqty'), prop: 'fqty', align: 'right', width: '80' },
        { label: this.$t('market.ftaxPrice'), prop: 'ftaxPrice', align: 'right', width: '80' },
        { label: this.$t('market.deliveryDate'), prop: 'fdeliveryDate' },
        { label: this.$t('market.note'), prop: 'fnote' },
        { label: this.$t('market.paezText2'), prop: 'fpaezText2' },
        {
          label: this.$t('market.fdescripTion'),
          prop: 'fdescripTion',
          minWidth: '300px'
        }
      ],
      tableHeader1: [],
      tableHeight: '70vh'
    }
  },
  created() {
    this.detailsList()
    this.tableHeader1 = this.detailsHeader
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 240px)' : '70vh'
  },
  methods: {
    // 复制
    async copyOrder(ev) {
      this.$router.push({ path: '/createMarkerOrder', query: {
        fid: this.selectIds[0],
        type: ev
      }})
    },
    // 导出表格-销售订单明细列表
    handleExportDetails() {
      require.ensure([], () => {
        const tHeader = this.detailsHeader.map((res) => {
          return res.label
        })
        const filterVal = this.detailsHeader.map((res) => {
          return res.prop
        })
        if (this.detailsData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else if (this.val && this.val.length > 0) {
          const list = this.val.map(item => {
            if (item.fcloseStatus === 'A') {
              item.fcloseStatus = '正常'
            } else {
              item.fcloseStatus = '已关闭'
            }
            return toMxAmina(item)
          })
          const data = formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, '销售预测列表')
        } else {
          queryTSalFoList({
            pageSize: 100000,
            pageNum: 1,
            search: this.searCollData
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.array.map(item => {
                if (item.fcloseStatus === 'A') {
                  item.fcloseStatus = '正常'
                } else {
                  item.fcloseStatus = '已关闭'
                }
                return toMxAmina(item)
              })
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, '销售预测列表')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    },
    // 销售预测明细列表
    async detailsList(ev) {
      this.loading = true
      this.details = []
      if (ev && !ev.page) {
        this.details = ev
      }
      const DATA = {
        pageNum: this.currentPageDetail,
        pageSize: this.sizeDetail,
        search: this.searCollData.concat(this.details)
      }
      const { data: RES } = await queryTSalFoList(DATA)
      this.detailsData = RES.array.map(item => {
        return toMxAmina(item)
      })
      this.totalDatail = RES.total
      this.loading = false
    },
    detailsListHandle(ev) {
      this.currentPageDetail = 1
      if (ev && ev.fname) {
        this.searchSon = ev.detail
        this.customHandle(ev)
        this.detailsList(ev.detail)
      } else {
        this.detailsList()
      }
    },
    // 查询物料
    detailMateriel(FNUMBER) {
      this.$router.push({ path: `/detailMateriel/${FNUMBER}` })
    },
    // 查看报表
    queryReportForm() {
      const FNUMBER = this.detailVal
      this.$router.push({ path: `/marketForm/${FNUMBER}` })
    },
    // 明细列表 多选时触发的事件
    selectionDatas(val) {
      this.detailVal = ''
      this.detailVal = val[0].fbillNo
      this.fbillno = val[0].fbillNo
      this.selectVal = []
      this.selectIds = []
      this.fentryData = []
      this.fidsData = []
      this.val = val
      val.forEach(res => {
        res.fbillNo && this.selectVal.push(res.fbillNo)
        this.selectIds.push(res.fid)
        this.fentryData.push(res.fentryId)
        this.fidsData.push(res.fid)
      })
      this.fidsData = Array.from(new Set(this.fidsData))
    },
    // 订单详情
    detailPurchase(ev) {
      const id = ev.fid || ev
      this.$router.push({ path: `/forecastDetail/${id}` })
    },
    // 新增
    addMateril() {
      this.$router.push({ path: '/createForecast' })
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = { Numbers: this.selectVal }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.selectVal = []
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
        this.detailsList()
      })
    },
    // 审批通过
    async audit(ev) {
      if (this.selectVal.length === 0) {
        this.$message({ showClose: true, message: '请选择数据', type: 'warning' })
        return
      }
      const api = ev === 1 ? reviewSalFo : notreviewSalFo
      this.toExamineFun(api)
    },
    // 提交、反提交
    async submit(ev) {
      const api = ev === 1 ? submitSalFo : notsubmitSalFo
      this.toExamineFun(api)
    },
    // 启用、禁用
    async using(ev) {
      const api = ev === 1 ? unCloseSalFo : closeSalFo
      this.toExamineFun(api)
    },
    // 删除
    delPublic() {
      this.$confirm('此操作将永久删除该订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const api = delSalFo
        this.toExamineFun(api)
      })
    },
    // 下推采购订单
    pushDownOrder() {
      if (this.orderLX === this.$t('menu.purOrderAsi')) {
        const DATA = {
          SoucrceIds: this.fidsData,
          EntryIds: this.fentryData,
          fbillTypeId: this.fbillTypeId
        }
        pushSalorder(DATA).then(res => {
          if (res.code === 0) {
            this.$router.push({
              path: `/editPurchase/${res.data.fid}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.deliveryRelease')) {
        const DATA = {
          SoucrceIds: this.fidsData,
          EntryIds: this.fentryData,
          fbillTypeId: this.fbillTypeId
        }
        queryPushDelSal(DATA).then(RES => {
          if (RES.code === 0) {
            this.$router.push({
              path: `/editDelivery/${RES.data}`
            })
          } else {
            this.$confirm(RES.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
        this.isdanjuDialog = false
      }
    },
    // 下推采购订单
    pushDown() {
      this.isdanjuDialog = true
      this.purpoorder('SX_PUR_POORDER')
    },
    orderWat(ev) {
      if (ev === this.$t('menu.deliveryRelease')) {
        this.purpoorder('SX_DELIVERYNOTICE')
        this.convert = this.$t('market.xacai')
        this.fbillTypeId = 199
      } else if (ev === this.$t('menu.purOrderAsi')) {
        this.purpoorder('SX_PUR_POORDER')
        this.convert = this.$t('market.xafa')
        this.fbillTypeId = 159
      }
    },
    // 采购订单单据
    async purpoorder(ev) {
      const { data: RES } = await queryViewItem({ viewName: ev })
      this.billTypeData = RES.list
    },
    // 自定义合计行
    getSummaries(param) {
      const { columns } = param
      const sums = []
      columns.forEach(() => {
        sums[0] = '合计'
        sums[8] = numFormat(this.totalQty)
        sums[10] = numFormat(this.totalTaxPrice)
      })
      return sums
    },
    // 自定义列表
    customHandle(ev) {
      this.tableHeaders = []
      if (ev.header) {
        ev.header.forEach(item => {
          this.tableHeader1.forEach(res => {
            if (res.label === item) {
              this.tableHeaders.push(res)
            }
          })
        })
        this.detailsHeader = this.tableHeaders
      } else if (ev.fname === '缺省方案') {
        this.detailsHeader = this.oldTabHeader
      } else {
        this.detailsHeader = this.tableHeader1
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.content {
  @include listBom;
    .el-table {
      overflow: visible !important;
      position: relative;
      &::v-deep .el-table__footer-wrapper {
        font-size: 13px;
        position: absolute;
        bottom: 0;
      }
    }
    .header {
      position: relative;

      .header-name {
        width: 100%;
      }

      .btn {
        transform: translateY(18%);
        margin-left: 450px !important;
      }
    }
  }

.inTheBtn {
  transform: translateY(-15px);
}

.tag-mar {
  margin-right: 3px;
  margin-bottom: 3px;
}

.tag-mar:hover {
  cursor: pointer;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
